#include<bits/stdc++.h>
using namespace std;
#define int long long

struct node
{
	int a, b;
}f[20010];

signed main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
//	freopen("D://desktop//p1496_8.in", "r", stdin);
	int n;
	cin>>n;
	for(int i = 1;i <= n;i++)
	{
		cin>>f[i].a>>f[i].b;
	}
	sort(f+1, f+n+1, [](const node& a, const node& b){
		return a.b < b.b;
	});
	
	int ans = 0, pre = f[n].b;
	for(int i = n;i >= 1;i--)
	{
		if(f[i].b < pre)
			ans += f[i].b - f[i].a;
		else if(f[i].a < pre)
			ans += pre - f[i].a;
		else
			continue;
		pre = f[i].a;
	}
	cout<<ans;
	return 0;
}
